package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author shiminghui
 * @date 2024/12/12 12:22
 * @description: 监听消息, 添加文章数据到ES中
 */
@Component
@Slf4j
public class SyncArticleListener {
    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC) // 监听ARTICLE_ES_SYNC_TOPIC的主题
    public void handleAddMsg(String json) {
        log.info("监听到消息:{}", json);
        if (json == null || json.length() == 0) {
            return;
        }
        // 消息处理
        SearchArticleVo searchArticleVo = JSON.parseObject(json, SearchArticleVo.class);
        if (searchArticleVo == null) {
            log.error("消息格式错误");
            return;
        }

        // 添加到es(二次添加覆盖)
        IndexRequest indexRequest = new IndexRequest("app_info_article");
        indexRequest.id(searchArticleVo.getId().toString()).source(json, XContentType.JSON);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("添加数据到ES失败,错误信息为{}", e.getMessage());
        }
    }

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_DOWN_TOPIC)
    public void handleDeleteMsg(String articleId) {
        log.info("监听到消息:{}", articleId);
        if (articleId == null || articleId.length() == 0) {
            return;
        }

        // 从es中删除
        DeleteRequest deleteRequest = new DeleteRequest("app_info_article", articleId);
    }

}
